import 'dart:convert';

import 'package:distribution_mall_flutter/assets.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/dialog/two_result_hint_dialog.dart';
import 'package:distribution_mall_flutter/entity/address/address_entity.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/pages/address/address_create_edit/address_created_edit.dart';
import 'package:distribution_mall_flutter/pages/address/select_address/select_address_provider.dart';
import 'package:distribution_mall_flutter/pages/goods/product_details/product_details_provider.dart';
import 'package:distribution_mall_flutter/router/router.gr.dart';
import 'package:distribution_mall_flutter/widgets/address_item.dart';
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';

class EPModalAddressPage extends ConsumerStatefulWidget {
  final Function(AddressItem arg)? footerCallback;

  const EPModalAddressPage({super.key, this.footerCallback});

  @override
  ConsumerState createState() => _EPModalAddressPage();
}

class _EPModalAddressPage extends ConsumerState<EPModalAddressPage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      ref.read(userAddressProvider.notifier).refresh();
    });
  }

  @override
  Widget build(BuildContext context) {
    final addressList =
        ref.watch(userAddressProvider.select((e) => e.addressList));
    final isEditMode = ref.watch(addressEditModeProvider);
    return Container(
      constraints:
          BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.8),
      margin: const EdgeInsets.only(left: 24, right: 24),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            padding: EdgeInsets.only(top: 26),
            child: Stack(
              children: [
                Center(
                  child: Text(
                    S.current.address_select,
                    style: const TextStyle(fontSize: 18, color: Colors.black),
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.pop(context);
                    },
                    child: const Icon(Icons.close_outlined,
                        size: 26, color: Color.fromRGBO(3, 0, 0, 1)),
                  ),
                )
              ],
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 40, bottom: 7),
            child: Row(
              children: [
                const Text(
                  'All addresses',
                  style: TextStyle(
                    color: Color(0xFF868D96),
                    fontSize: 14,
                  ),
                ),
                const Spacer(),
                GestureDetector(
                  onTap: () {
                    ref
                        .watch(addressEditModeProvider.notifier)
                        .triggerEditMode();
                  },
                  behavior: HitTestBehavior.opaque,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Image.asset(
                        Assets.assets_icons_address_edit_png,
                        width: 16,
                      ),
                      Text(
                        isEditMode ? 'Complete' : 'Manage',
                        style: const TextStyle(
                          color: Color(0xFF868D96),
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          const Divider(
            height: 1,
          ),
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: [
                  ...addressList.map((e) => EPAddressItem(
                        data: e,
                        isEditMode: isEditMode,
                        itemCallback: (data) {
                          Navigator.pop(context, data);
                        },
                        defCallback: (bol) {
                          ref.read(userAddressProvider.notifier).updateIsDef({
                            'distributorAddressId': e.distributorAddressId,
                            'distributorId': e.distributorId,
                            'isDef': bol,
                          });
                        },
                        editCallback: () {
                          appRouter.push(AddressCreateEditRoute(
                            type: AddressActionType.edit.name,
                            selectItem: jsonEncode(e.toJson()),
                          ));
                        },
                        delCallback: () async {
                          bool? result = await showDialog(
                              context: context,
                              builder: (_) => const TwoResultHintDialog(
                                    title: 'Delete this shipping address？',
                                    leftText: 'Cancel',
                                    rightText: 'Confirm',
                                  ));
                          if (result == true) {
                            ref
                                .read(userAddressProvider.notifier)
                                .deleteAddress(e);
                          }
                        },
                      )),
                ],
              ),
            ),
          ),
          Container(
              height: 42,
              margin: const EdgeInsets.only(bottom: 19),
              width: double.infinity,
              child: ElevatedButton(
                  onPressed: () {
                    appRouter.push(AddressCreateEditRoute(
                        type: AddressActionType.add.name));
                  },
                  child: Text(S.current.address_add)))
        ],
      ),
    );
  }
}
